package com.example.demo.controller.admincontroller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.Result;
import com.example.demo.entity.Expert;
import com.example.demo.service.ExpertService;
import com.example.demo.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 专家管理控制器
 */
@RestController
@RequestMapping("/admin/expert")
public class ExpertManageController {

    @Autowired
    private ExpertService expertService;

    /**
     * 分页查询专家列表
     */
    @GetMapping("/list")
    public Result list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) Integer status
    ) {
        Page<Expert> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Expert> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (username != null && !username.isEmpty()) {
            wrapper.like(Expert::getUsername, username);
        }
        if (name != null && !name.isEmpty()) {
            wrapper.like(Expert::getName, name);
        }
        if (department != null && !department.isEmpty()) {
            wrapper.like(Expert::getDepartment, department);
        }
        if (status != null) {
            wrapper.eq(Expert::getStatus, status);
        }
        
        // 按创建时间降序排序
        wrapper.orderByAsc(Expert::getId);
        
        Page<Expert> expertPage = expertService.page(page, wrapper);
        return Result.success(expertPage);
    }

    /**
     * 获取专家详情
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        Expert expert = expertService.getById(id);
        if (expert == null) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        return Result.success(expert);
    }

    /**
     * 新增专家
     */
    @PostMapping
    public Result add(@RequestBody Expert expert) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<Expert> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Expert::getUsername, expert.getUsername());
        if (expertService.count(wrapper) > 0) {
            return Result.error(ErrorCode.USERNAME_EXIST);
        }
        
        // 加密密码
        expert.setPassword(MD5Utils.encrypt(expert.getPassword()));
        
        // 设置默认值
        expert.setStatus(1); // 默认启用
        expert.setCreateTime(new Date());
        expert.setUpdateTime(new Date());
        
        if (expertService.save(expert)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 修改专家信息
     */
    @PutMapping
    public Result update(@RequestBody Expert expert) {
        if (expert.getId() == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        
        // 检查专家是否存在
        Expert existExpert = expertService.getById(expert.getId());
        if (existExpert == null) {
            return Result.error(ErrorCode.SYSTEM_ERROR);
        }
        
        // 如果修改了用户名，需要检查是否重复
        if (!existExpert.getUsername().equals(expert.getUsername())) {
            LambdaQueryWrapper<Expert> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Expert::getUsername, expert.getUsername());
            if (expertService.count(wrapper) > 0) {
                return Result.error(ErrorCode.USERNAME_EXIST);
            }
        }
        
        // 如果提供了新密码，需要加密
        if (expert.getPassword() != null && !expert.getPassword().isEmpty()) {
            expert.setPassword(MD5Utils.encrypt(expert.getPassword()));
        } else {
            expert.setPassword(null); // 不更新密码
        }
        
        expert.setUpdateTime(new Date());
        if (expertService.updateById(expert)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 删除专家
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        if (expertService.removeById(id)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }

    /**
     * 修改专家状态
     */
    @PutMapping("/status")
    public Result updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        if (status != 0 && status != 1) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        
        Expert expert = new Expert();
        expert.setId(id);
        expert.setStatus(status);
        expert.setUpdateTime(new Date());
        
        if (expertService.updateById(expert)) {
            return Result.success();
        }
        return Result.error(ErrorCode.OPERATION_ERROR);
    }
} 